@page "/system/logs"
@using Blazor.Server.UI.Pages.SystemManagement.Components
@using CleanArchitecture.Blazor.Application.Features.Logs.DTOs
@using CleanArchitecture.Blazor.Application.Features.Logs.Queries.ChatData
@using CleanArchitecture.Blazor.Application.Logs.Queries.PaginationQuery

@attribute [Authorize(Policy = Permissions.Logs.View)]
@inject IStringLocalizer<Logs> L
<PageTitle>@L[Title]</PageTitle>
<style>
    .mud-table-toolbar {
        height: 84px !important;
    }
</style>
<ErrorBoundary>
    <ChildContent>
        <Blazor.Server.UI.Pages.SystemManagement.Components.LogsLineCharts @ref="chartcomponent" Data="_data"></Blazor.Server.UI.Pages.SystemManagement.Components.LogsLineCharts>
        <MudTable ServerData="@(new Func<TableState, Task<TableData<LogDto>>>(ServerReload))"
                  FixedHeader="true"
                  FixedFooter="true"
                  Virtualize="true"
                  Height="calc(100vh - 265px)"
                  Style="min-height:700px"
                  Loading="@_loading"
                  SortLabel="@L["Order By"]"
                  Hover="true" @ref="_table">
            <ToolBarContent>
                <div class="justify-start pt-3">
                    <MudText Typo="Typo.h6">@L["Logs"]</MudText>
                    <MudButton DisableElevation Variant="Variant.Outlined"
                               Size="Size.Small"
                               Disabled="@_loading"
                               OnClick="@(()=>OnRefresh())"
                               StartIcon="@Icons.Material.Filled.Refresh" IconColor="Color.Surface" Color="Color.Primary"
                               Style="margin-right: 5px;">@L["Refresh"]</MudButton>
                </div>
                <MudSpacer />
                <MudTextField T="string" ValueChanged="@(s=>OnSearch(s))" Value="@_searchString" Placeholder="Search" Adornment="Adornment.Start"
                              AdornmentIcon="@Icons.Material.Filled.Search" IconSize="Size.Medium" Class="mt-0"></MudTextField>
            </ToolBarContent>
            <ColGroup>
                <MudHidden Breakpoint="Breakpoint.SmAndDown">
                    <col style="width:110px;" />
                    <col style="width:120px;" />
                    <col style="width:90px;" />
                    <col />
                    <col />
                </MudHidden>
            </ColGroup>
            <HeaderContent>
                <MudTh>@L["Action"]</MudTh>
                <MudTh><MudTableSortLabel SortLabel="TimeStamp" T="LogDto">@L["Time Stamp"]</MudTableSortLabel></MudTh>
                <MudTh Style="text-align:center"><MudTableSortLabel SortLabel="Level" T="LogDto">@L["Level"]</MudTableSortLabel></MudTh>
                <MudTh><MudTableSortLabel SortLabel="Message" T="LogDto">@L["Message"]</MudTableSortLabel></MudTh>
                <MudTh><MudTableSortLabel SortLabel="UserName" T="LogDto">@L["User Name"]</MudTableSortLabel></MudTh>
            </HeaderContent>
            <RowTemplate>
                <MudTd DataLabel="@L["Action"]">
                    <MudButton Variant="Variant.Filled" DisableElevation="true"
                               OnClick="@(() => OnShowDetail(context))"
                               StartIcon="@(context.ShowDetails == true?Icons.Material.Filled.Close:Icons.Material.Filled.Add)" IconColor="Color.Secondary" Size="Size.Small"
                               Color="Color.Surface">
                        @L[((context.ShowDetails == true) ? "Hide" : "Show") + " Details"]
                    </MudButton>
                </MudTd>
                <MudTd DataLabel="@L["Time Stamp"]">
                    @context.TimeStamp.ToString("yyyy-MM-dd HH:mm:ss")
                </MudTd>
                <MudTd Style="text-align:center" DataLabel="@L["Level"]">
                    @switch (context.Level)
                    {
                        case "Trace":
                            <MudChip Label="true">@context.Level</MudChip>
                            break;
                        case "Debug":
                            <MudChip Label="true">@context.Level</MudChip>
                            break;
                        case "Information":
                            <MudChip Color="Color.Info" Label="true">@context.Level</MudChip>
                            break;
                        case "Warning":
                            <MudChip Color="Color.Warning" Label="true">@context.Level</MudChip>
                            break;
                        case "Error":
                            <MudChip Color="Color.Error" Label="true">@context.Level</MudChip>
                            break;
                        case "Critical":
                            <MudChip Color="Color.Error" Label="true">@context.Level</MudChip>
                            break;
                        default:
                            <MudChip Label="true">@context.Level</MudChip>
                            break;
                    }

                </MudTd>
                <MudTd DataLabel="@L["Message"]">
                    @context.Message
                </MudTd>
                <MudTd DataLabel="@L["User Name"]">
                    @context.UserName
                </MudTd>
            </RowTemplate>
            <ChildRowContent>
                @if (context.ShowDetails)
                {
                    <MudTr>
                        <td colspan="5">
                            <MudCard Elevation="0">
                                <MudCardHeader>
                                    <CardHeaderContent>
                                        <MudText Typo="Typo.body1"><strong>@context.Level</strong></MudText>
                                    </CardHeaderContent>
                                </MudCardHeader>
                                <MudCardContent Class="pt-0">
                                    <MudText>Message</MudText>
                                    <MudText Typo="Typo.body2">@context.Message</MudText>
                                    @if (!string.IsNullOrEmpty(context.Exception))
                                    {
                                        <MudText Color="Color.Error">Exception</MudText>
                                        <MudText Color="Color.Warning" Typo="Typo.body2">@context.Exception</MudText>
                                    }
                                    <MudText>Client IP</MudText>
                                    <MudText Typo="Typo.body2">@context.ClientIP</MudText>
                                </MudCardContent>
                            </MudCard>
                        </td>
                    </MudTr>
                }
            </ChildRowContent>
            <NoRecordsContent>
                <MudText>@L["NOMACHING"]</MudText>
            </NoRecordsContent>
            <LoadingContent>
                <MudText>@L["Loading"]</MudText>
            </LoadingContent>
            <PagerContent>
                <MudTablePager />
            </PagerContent>
        </MudTable>
    </ChildContent>
    <ErrorContent>
        <CustomError Exception="context"></CustomError>
    </ErrorContent>
</ErrorBoundary>
@code {
    private LogsLineCharts? chartcomponent;
    public string Title { get; private set; } = "Logs";
    private string _searchString = string.Empty;
    private MudTable<LogDto> _table = default!;

    public List<LogTimeLineDto> _data { get; set; } = new();
    private bool _loading;
    [Inject]
    private ISender _mediator { get; set; } = default!;

    protected override void OnInitialized()
    {
        Title = L["Logs"];
    }
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            _data = await _mediator.Send(new LogsTimeLineChatDataQuery());
            StateHasChanged();
            await chartcomponent!.RenderChart();
          
        }
    }

    private async Task<TableData<LogDto>> ServerReload(TableState state)
    {
        try
        {
            _loading = true;
            var request = new LogsWithPaginationQuery()
                {
                    Keyword = _searchString,
                    OrderBy = string.IsNullOrEmpty(state.SortLabel) ? "Id" : state.SortLabel,
                    SortDirection = (state.SortDirection == SortDirection.None ? SortDirection.Descending.ToString() : state.SortDirection.ToString()),
                    PageNumber = state.Page + 1,
                    PageSize = state.PageSize
                };
            var result = await _mediator.Send(request).ConfigureAwait(false);
            return new TableData<LogDto>() { TotalItems = result.TotalItems, Items = result.Items };
        }
        finally
        {
            _loading = false;
        }
    }
    private async Task OnSearch(string text)
    {
        _searchString = text;
        await _table.ReloadServerData();
    }
    private async Task OnRefresh()
    {
        _searchString = string.Empty;
        await _table.ReloadServerData();
    }
    private Task OnShowDetail(LogDto dto)
    {
        dto.ShowDetails = !dto.ShowDetails;
        return Task.CompletedTask;
    }
}
